package com.zjcloud.framework.config;

import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.proxy.jdbc.JdbcParameter;
import com.alibaba.druid.proxy.jdbc.ResultSetProxy;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Map;

/**
 * Druid SQL执行监控过滤器
 *
 * @author zjcloud
 */
public class DruidSqlLogFilter extends FilterEventAdapter {

    private static final Logger log = LoggerFactory.getLogger(DruidSqlLogFilter.class);

    @Override
    protected void statementExecuteBefore(StatementProxy statement, String sql) {
        log.debug("执行SQL开始: {}", sql);
    }

    @Override
    protected void statementExecuteAfter(StatementProxy statement, String sql, boolean result) {
        log.debug("执行SQL结束: {}, 结果: {}", sql, result);
    }

    @Override
    protected void statementExecuteQueryBefore(StatementProxy statement, String sql) {
        log.debug("执行查询SQL开始: {}", sql);
    }

    @Override
    protected void statementExecuteQueryAfter(StatementProxy statement, String sql, ResultSetProxy resultSet) {
        log.debug("执行查询SQL结束: {}", sql);
    }

    @Override
    protected void statementExecuteUpdateBefore(StatementProxy statement, String sql) {
        log.debug("执行更新SQL开始: {}", sql);
    }

    @Override
    protected void statementExecuteUpdateAfter(StatementProxy statement, String sql, int updateCount) {
        log.debug("执行更新SQL结束: {}, 影响行数: {}", sql, updateCount);
    }

    @Override
    protected void statement_executeErrorAfter(StatementProxy statement, String sql, Throwable error) {
        log.error("执行SQL异常: {}, 异常信息: {}", sql, error.getMessage());
    }

    @Override
    public void statement_close(FilterChain chain, StatementProxy statement) throws SQLException {
        super.statement_close(chain, statement);
        Map<Integer, JdbcParameter> parameters = statement.getParameters();
        if (parameters != null && !parameters.isEmpty() && statement.getBatchSql() != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("关闭Statement, SQL: ").append(statement.getBatchSql());
            sb.append(", 参数: ");
            for (Map.Entry<Integer, JdbcParameter> entry : parameters.entrySet()) {
                sb.append(entry.getKey()).append("=");
                JdbcParameter parameter = entry.getValue();
                if (parameter != null) {
                    sb.append(parameter.getValue());
                } else {
                    sb.append("null");
                }
                sb.append(", ");
            }
            log.debug(sb.toString());
        }
    }
}